package luceneppt;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.apache.poi.hslf.extractor.PowerPointExtractor;

public class IndexaPpt {
	public IndexaPpt(){
	   try{
		    File indexDir = new File("c:\\indexdir");
		    File dataDir = new File("d:\\temp2");
		    long start = new Date().getTime();
		    int numIndexed = index(indexDir, dataDir);
		    long end = new Date().getTime();
		    System.out.println("Se han indizado " + numIndexed + " archivos          en " + (end - start) + " milisegundos");
	   }
	   catch(Exception err){}
		
	}
	
	public static int index(File indexDir, File dataDir)
    throws IOException {
    if (!dataDir.exists() || !dataDir.isDirectory()) {
      throw new IOException(dataDir
        + " no existe o no es un directorio ");
    }
    Directory directory = FSDirectory.open(indexDir);
    borrarDirectorio(indexDir);
    
    IndexWriter writer = new IndexWriter(directory, new StandardAnalyzer(Version.LUCENE_30), IndexWriter.MaxFieldLength.LIMITED);
    writer.setUseCompoundFile(false);
    indexDirectory(writer, dataDir);
    int numIndexed = writer.numDocs();
    writer.optimize();
    directory.close();
    writer.close();
    return numIndexed;
  }
	
	  private static void borrarDirectorio(File dir){
		  File[] ficheros = dir.listFiles();
		  for (int x=0;x<ficheros.length;x++){
			  if (ficheros[x].isDirectory()) {
				  System.out.print("Borrando: "+ficheros[x]);
				  borrarDirectorio(ficheros[x]);
				}
			  System.out.print("Borrando: "+ficheros[x]);
			  ficheros[x].delete();
		  }
	  }
	  
	  private static void indexDirectory(IndexWriter writer, File dir)
	    throws IOException {
	    File[] files = dir.listFiles();
	    for (int i = 0; i < files.length; i++) {
	      File f = files[i];
	      if (f.isDirectory()) {
	        indexDirectory(writer, f);  // recurse
	      } else if (f.getName().endsWith(".ppt")) {
	        indexFile(writer, f);
	      }
	    }
	  }
	  

	  private static void indexFile(IndexWriter writer, File f)
	    throws IOException {
		  try{
	    
		   if (f.isHidden() || !f.exists() || !f.canRead()) {
		      return;
		    }
		    System.out.println("Indizando " + f.getCanonicalPath());
		    Document doc = new Document();
		    doc.add(new Field("filename", f.getCanonicalPath(), Field.Store.YES, Field.Index.ANALYZED));
		    
		    PowerPointExtractor pw = new PowerPointExtractor(new FileInputStream(f));
		    doc.add(new Field("Contenido", pw.getText(),Field.Store.YES, Field.Index.ANALYZED ));
		    if (pw.getSummaryInformation().getAuthor() == null){
			       doc.add(new Field("Autor","Sin Autor", Field.Store.YES, Field.Index.ANALYZED));
			}
			else{
			        doc.add(new Field("Autor", pw.getSummaryInformation().getAuthor(), Field.Store.YES, Field.Index.ANALYZED) );
			}
		    if (pw.getSummaryInformation().getCreateDateTime().toLocaleString().substring(0,10) == null){
			       doc.add(new Field("Fecha","Sin fecha", Field.Store.YES, Field.Index.ANALYZED));
			}
			else{
				doc.add(new Field("Fecha", pw.getSummaryInformation().getCreateDateTime().toLocaleString().substring(0,10), Field.Store.YES, Field.Index.ANALYZED) );
			}
		    doc.add(new Field("Tipo", "ppt", Field.Store.YES, Field.Index.ANALYZED));
		    System.out.println(pw.getSummaryInformation().getAuthor());
		    System.out.println(pw.getSummaryInformation().getCreateDateTime().toLocaleString().substring(0,10));
		    writer.addDocument(doc);
		    writer.optimize();
		    writer.commit();
	  }
	  catch(Exception err){
		  System.out.println("Erro: "+err);
	  }
	}

}
